# Web服务器，提供前端推送服务
from flask import Flask, Response, jsonify, render_template_string
from flask_cors import CORS
import json
import time
import threading
import logging
from typing import Dict, Any, Optional
from ..utils.frame_utils import FrameUtils


class WebServer:
    """Web服务器，处理前端视频流推送"""

    def __init__(self, server_config: Dict[str, Any]):
        """
        初始化Web服务器
        Args:
            server_config: 服务器配置
        """
        self.app = Flask(__name__)
        CORS(self.app)  # 允许跨域

        self.config = server_config
        self.current_frame_data = None
        self.frame_lock = threading.Lock()
        self.frame_utils = FrameUtils()

        # 配置路由
        self._setup_routes()

        logging.info("Web服务器初始化完成")

    def _setup_routes(self):
        """设置路由"""

        @self.app.route('/')
        def index():
            """主页面"""
            html_template = """
            <!DOCTYPE html>
            <html>
            <head>
                <title>YOLOv8 实时检测</title>
                <style>
                    body { font-family: Arial, sans-serif; margin: 20px; }
                    .container { max-width: 1000px; margin: 0 auto; }
                    .video-container { text-align: center; margin: 20px 0; }
                    img { max-width: 100%; height: auto; border: 1px solid #ccc; }
                    .info { background: #f5f5f5; padding: 10px; margin: 10px 0; border-radius: 5px; }
                </style>
            </head>
            <body>
                <div class="container">
                    <h1>YOLOv8 实时目标检测</h1>
                    <div class="info">
                        <p>检测目标：人(红框)、电脑(绿框)、杯子(绿框)</p>
                        <p>视频源：RTSP流</p>
                    </div>
                    <div class="video-container">
                        <img id="videoStream" src="/video_feed" alt="视频加载中...">
                    </div>
                </div>

                <script>
                    // 自动刷新图片以获取最新帧
                    function refreshImage() {
                        const img = document.getElementById('videoStream');
                        const timestamp = new Date().getTime();
                        img.src = '/video_feed?t=' + timestamp;
                    }

                    // 每100ms刷新一次(10fps)
                    setInterval(refreshImage, 100);
                </script>
            </body>
            </html>
            """
            return html_template

        @self.app.route('/video_feed')
        def video_feed():
            """视频流端点"""

            def generate():
                while True:
                    with self.frame_lock:
                        if self.current_frame_data:
                            # 返回MJPEG格式的流
                            yield (b'--frame\r\n'
                                   b'Content-Type: image/jpeg\r\n\r\n' +
                                   self.current_frame_data + b'\r\n')
                    time.sleep(1.0 / self.config['max_fps'])  # 控制帧率

            return Response(generate(),
                            mimetype='multipart/x-mixed-replace; boundary=frame')

        @self.app.route('/latest_frame')
        def latest_frame():
            """获取最新帧的API端点"""
            with self.frame_lock:
                if self.current_frame_data:
                    # 返回base64编码的图片
                    import base64
                    frame_base64 = base64.b64encode(self.current_frame_data).decode('utf-8')
                    return jsonify({
                        'success': True,
                        'frame_data': f"data:image/jpeg;base64,{frame_base64}",
                        'timestamp': time.time()
                    })
                else:
                    return jsonify({
                        'success': False,
                        'message': '暂无可用帧'
                    })

        @self.app.route('/status')
        def status():
            """系统状态API"""
            return jsonify({
                'status': 'running',
                'timestamp': time.time(),
                'has_frame': self.current_frame_data is not None
            })

    def update_frame(self, frame_data: bytes):
        """
        更新当前帧数据
        Args:
            frame_data: 编码后的帧数据
        """
        with self.frame_lock:
            self.current_frame_data = frame_data

    def start_server(self):
        """启动Web服务器"""
        try:
            self.app.run(
                host=self.config['host'],
                port=self.config['port'],
                debug=False,
                threaded=True
            )
        except Exception as e:
            logging.error(f"启动Web服务器失败: {e}")

    def start_server_thread(self):
        """在新线程中启动Web服务器"""
        server_thread = threading.Thread(target=self.start_server)
        server_thread.daemon = True
        server_thread.start()
        logging.info(f"Web服务器已启动: http://{self.config['host']}:{self.config['port']}")